﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using black_screen_client.Models;
using System.Security.Policy;

namespace black_screen_client
{
    public class TcpClientHelper
    {

        public bool IsAutoStop { get; set; } = false;
        /// <summary>
        /// 是否连接上
        /// </summary>
        public bool ConnectFlag { get; set; } = false;
        /// <summary>
        /// 监听的IP
        /// </summary>
        private string Ip { get; set; }
        /// <summary>
        /// 监听的端口
        /// </summary>
        private int Port { get; set; }
        /// <summary>
        /// 监听每次读取字节数
        /// </summary>
        private byte[] Buffer { get; set; }
        /// <summary>
        /// 连接套间字
        /// </summary>
        private Socket SocketC { get; set; }
        /// <summary>
        /// 监听线程
        /// </summary>
        private Thread ListenMsgTh { get; set; }
        /// <summary>
        /// 监听线程
        /// </summary>
        private Thread ReConnectTh { get; set; }
        /// <summary>
        /// 连接事件
        /// </summary>
        public event Action<string> SocketMessage;
        /// <summary>
        /// 接收消息
        /// </summary>
        public event Action<byte[], int> SocketReceive;
        /// <summary>
        /// 接收消息
        /// </summary>
        public event Action<byte[], int> SocketSend;
        /// <summary>
        /// 重连标志
        /// </summary>
        private bool ReConnnectFlag { get; set; } = false;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip">连接服务器的IP</param>
        /// <param name="port">连接服务器的端口</param>
        public TcpClientHelper( int bufferLength = 1024 * 1024)
        {
            TcpServerModel serverModel = ProjectTools.getTcpServer();
            Ip = serverModel.IpAddress;
            Port = serverModel.PortNumber;
            Buffer = new byte[bufferLength];
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="count">重连次数</param>
        /// <param name="delayTime">重连时间</param>
        public bool Init()
        {
            //连接
            if (!Connect())
                return false;
            //监听
            if (SocketC.Connected)
            {
                IsAutoStop = false;
                ListenMsgTh = new Thread(receive);
                ListenMsgTh.IsBackground = true;
                ListenMsgTh.Start();
            }
            return true;
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        private bool Connect()
        {
            // 重置之前可能存在的Socket
            if (SocketC != null)
            {
                try
                {
                    SocketC.Close();
                }
                catch (Exception ex)
                {
                    Logger.Singleton.Warn("关闭旧Socket连接时出错: " + ex.Message);
                }
                finally
                {
                    SocketC = null;
                }
            }
            
            try
            {
                Logger.Singleton.Info($"开始连接服务器: {Ip}:{Port}");
                
                // 1. 实例化套接字(IP4寻址地址,流式传输,TCP协议)
                SocketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                
                // 2. 设置Socket选项，增强在多屏环境下的稳定性
                SocketC.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                SocketC.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                SocketC.ReceiveTimeout = 30000; // 30秒接收超时
                SocketC.SendTimeout = 10000;   // 10秒发送超时
                
                // 3. 创建IP对象并建立连接
                IPAddress address = IPAddress.Parse(Ip);
                IPEndPoint endPoint = new IPEndPoint(address, Port);
                
                // 4. 使用异步连接，避免在主线程上阻塞
                IAsyncResult result = SocketC.BeginConnect(endPoint, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(5000, true); // 5秒连接超时
                
                if (!success || !SocketC.Connected)
                {
                    // 连接超时或连接失败
                    SocketC.Close();
                    SocketC = null;
                    Logger.Singleton.Error($"连接服务器[{Ip}:{Port}]超时！");
                    return ConnectFlag = false;
                }
                
                // 5. 完成连接
                SocketC.EndConnect(result);
                
                // 6. 记录成功连接
                Logger.Singleton.Info($"客户端成功连接到服务器: {Ip}:{Port}");
                
                // 7. 更新连接状态标志
                return ConnectFlag = true;
            }
            catch (SocketException ex)
            {
                Logger.Singleton.Error($"网络故障，客户端[{Ip}:{Port}]连接失败！Socket错误码: {ex.SocketErrorCode} - {ex.Message}", ex);
                ConnectFlag = false;
                SocketC = null;
                return false;
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($"连接服务器时发生未预期异常: {ex.Message}", ex);
                ConnectFlag = false;
                SocketC = null;
                return false;
            }
        }

        public void Stop()
        {
            ReConnnectFlag = false;
            ConnectFlag = false;
            IsAutoStop = true;

            // 中断线程
            if (ListenMsgTh != null && ListenMsgTh.IsAlive)
            {
                ListenMsgTh.Interrupt();
            }
            if (ReConnectTh != null && ReConnectTh.IsAlive)
            {
                ReConnectTh.Interrupt();
            }

            // 关闭连接
            if (SocketC != null && SocketC.Connected)
            {
                try
                {
                    SocketC.Shutdown(SocketShutdown.Both);
                }
                catch (SocketException ex)
                {
                    Logger.Singleton.Error("关闭连接出错：" + ex.Message);
                }
                finally
                {
                    SocketC.Close();
                }
            }
        }

        /// <summary>
        /// 重新连接
        /// </summary>
        public void ReConnect(SocketException ex)
        {
            // 防止多线程调用导致的重复重连
            if (ReConnnectFlag || IsAutoStop)
            {
                Logger.Singleton.Debug("重连被跳过: 已有重连线程运行或手动停止");
                return;
            }
            
            // 使用原子操作设置重连标志
            bool wasSet = false;
            try
            {
                if (!ReConnnectFlag && !IsAutoStop)
                {
                    ReConnnectFlag = true;
                    wasSet = true;
                }
                else
                {
                    Logger.Singleton.Debug("重连标志设置失败: 可能已被其他线程设置或手动停止");
                    return;
                }
            }
            catch (Exception flagEx)
            {
                Logger.Singleton.Error("设置重连标志时出错: " + flagEx.Message);
                return;
            }
            
            if (!wasSet)
            {
                Logger.Singleton.Debug("重连操作被取消: 标志设置失败");
                return;
            }
            
            try
            {
                // 记录重连原因
                string reconnectReason = ex != null ? 
                    $"Socket错误: {ex.SocketErrorCode} - {ex.Message}" : 
                    "检测到服务器断开连接";
                
                Logger.Singleton.Info($"开始重连流程: {reconnectReason}");
                
                // 通知上层连接状态变化
                if (ex != null)
                {
                    SocketMessage?.Invoke($"网络连接异常: {ex.Message}");
                }
                else
                {
                    SocketMessage?.Invoke("服务器连接已断开，正在尝试重连...");
                }
                
                // 先安全地释放现有资源，但不重置ReConnnectFlag
                try
                {
                    // 这里不调用Close()以避免重置ReConnnectFlag
                    // 单独关闭连接和线程
                    if (SocketC != null)
                    {
                        try
                        {
                            SocketC.Shutdown(SocketShutdown.Both);
                        }
                        catch (Exception shutdownEx)
                        {
                            Logger.Singleton.Warn("关闭Socket时出错: " + shutdownEx.Message);
                        }
                        finally
                        {
                            SocketC.Close();
                            SocketC = null;
                        }
                    }
                    
                    // 安全地中断监听线程
                    if (ListenMsgTh != null && ListenMsgTh.IsAlive)
                    {
                        try
                        {
                            ListenMsgTh.Interrupt();
                        }
                        catch (Exception interruptEx)
                        {
                            Logger.Singleton.Warn("中断监听线程时出错: " + interruptEx.Message);
                        }
                    }
                }
                catch (Exception releaseEx)
                {
                    Logger.Singleton.Error("释放资源时出错: " + releaseEx.Message, releaseEx);
                    // 继续执行，不中断重连流程
                }
                
                // 重连
                ReConnectTh = new Thread(delegate ()
                {
                    string threadId = Thread.CurrentThread.ManagedThreadId.ToString();
                    int retryCount = 0;
                    int maxRetries = 15; // 增加最大重连次数到15次
                    int baseDelay = 3000; // 调整基础延迟时间为3秒
                    bool reconnected = false;
                    
                    Logger.Singleton.Info($"重连线程[{threadId}]已启动");
                    
                    try
                    {
                        // 循环重连，带指数退避策略和随机延迟
                        while (retryCount < maxRetries && !IsAutoStop)
                        {
                            retryCount++;
                            Logger.Singleton.Info($"重连尝试 #{retryCount}/{maxRetries} (线程ID: {threadId})");
                            
                            try
                            {
                                if (Connect())
                                {
                                    Logger.Singleton.Info("连接成功！");
                                    SocketMessage?.Invoke("连接成功！");
                                    
                                    // 重新开启监听
                                    if (SocketC?.Connected == true)
                                    {
                                        // 确保之前的监听线程已停止
                                        if (ListenMsgTh != null && ListenMsgTh.IsAlive)
                                        {
                                            try
                                            {
                                                ListenMsgTh.Interrupt();
                                            }
                                            catch (Exception)
                                            {}
                                        }
                                        
                                        ListenMsgTh = new Thread(receive)
                                        {
                                            IsBackground = true,
                                            Name = $"SocketReceiveThread_{DateTime.Now.Ticks}" // 唯一线程名，避免冲突
                                        };
                                        ListenMsgTh.Start();
                                        Logger.Singleton.Info("接收线程已重启");
                                    }
                                    
                                    reconnected = true;
                                    break;
                                }
                            }
                            catch (Exception connectEx)
                            {
                                Logger.Singleton.Error($"重连过程中连接失败: {connectEx.Message}", connectEx);
                            }
                            
                            // 指数退避策略 + 随机抖动，避免多屏环境下的重连风暴
                            double exponentialDelay = baseDelay * Math.Pow(2, Math.Min(retryCount - 1, 6)); // 最大指数级别为64
                            int jitter = new Random().Next(500, 1500); // 添加500-1500ms的随机抖动
                            int delayTime = Math.Min((int)exponentialDelay + jitter, 60000); // 最大延迟60秒
                            
                            Logger.Singleton.Info($"重连失败，{delayTime}ms后重试 (指数延迟: {exponentialDelay}ms, 随机抖动: {jitter}ms)");
                            
                            // 分段睡眠，以便在手动停止时能够及时响应
                            int remainingDelay = delayTime;
                            while (remainingDelay > 0 && !IsAutoStop)
                            {
                                int sleepInterval = Math.Min(remainingDelay, 1000); // 每次最多睡眠1秒
                                Thread.Sleep(sleepInterval);
                                remainingDelay -= sleepInterval;
                            }
                            
                            // 检查是否被手动停止
                            if (IsAutoStop)
                            {
                                Logger.Singleton.Info("重连过程中检测到手动停止");
                                break;
                            }
                        }
                        
                        if (!reconnected)
                        {
                            if (retryCount >= maxRetries)
                            {
                                Logger.Singleton.Error("达到最大重连次数，停止重连");
                                SocketMessage?.Invoke("多次重连失败，请检查网络连接或服务端状态");
                            }
                            else
                            {
                                Logger.Singleton.Info("重连已取消");
                            }
                        }
                    }
                    catch (ThreadInterruptedException)
                    {
                        Logger.Singleton.Info($"重连线程[{threadId}]被中断");
                    }
                    catch (Exception threadEx)
                    {
                        Logger.Singleton.Error($"重连线程[{threadId}]发生异常: {threadEx.Message}", threadEx);
                        SocketMessage?.Invoke($"重连过程发生错误: {threadEx.Message}");
                    }
                    finally
                    {
                        // 无论成功失败，都重置重连标志
                        try
                        {
                            ReConnnectFlag = false;
                            Logger.Singleton.Debug($"重连线程[{threadId}]结束，重连标志已重置");
                        }
                        catch (Exception flagEx)
                        {
                            Logger.Singleton.Error($"重置重连标志时出错: {flagEx.Message}");
                        }
                        
                        // 清理重连线程引用
                        if (ReConnectTh != null && ReConnectTh.ManagedThreadId.ToString() == threadId)
                        {
                            ReConnectTh = null;
                        }
                        
                        Logger.Singleton.Info($"重连线程[{threadId}]已完全退出");
                    }
                })
                {
                    IsBackground = true,
                    Name = $"SocketReconnectThread_{DateTime.Now.Ticks}" // 唯一线程名，避免冲突
                };
                
                try
                {
                    ReConnectTh.Start();
                    Logger.Singleton.Info("重连线程已启动");
                }
                catch (Exception startEx)
                {
                    Logger.Singleton.Error("启动重连线程失败: " + startEx.Message, startEx);
                    // 确保重置标志
                    ReConnnectFlag = false;
                }
            }
            catch (Exception outerEx)
            {
                Logger.Singleton.Error("重连过程中发生未预期异常: " + outerEx.Message, outerEx);
                // 确保重置标志
                try
                {
                    ReConnnectFlag = false;
                }
                catch (Exception)
                {}
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buffer">字节数组数据</param>
        public void sendMessage(byte[] buffer)
        {
            // 参数验证
            if (buffer == null || buffer.Length == 0)
            {
                Logger.Singleton.Warn("尝试发送空数据，已忽略");
                return;
            }
            
            // 安全发送数据，避免在Socket为null时引发空引用异常
            if (SocketC == null || !SocketC.Connected)
            {
                Logger.Singleton.Warn("Socket未连接，尝试重连后再发送数据");
                // 异步重连，避免阻塞调用线程
                Task.Run(() =>
                {
                    if (!IsAutoStop && !ReConnnectFlag)
                    {
                        ReConnect(null);
                    }
                });
                return;
            }
            
            try
            {
                // 分批发送数据，避免大数据包导致的问题
                int sentBytes = 0;
                int bufferSize = buffer.Length;
                int chunkSize = 8192; // 8KB的块大小
                
                Logger.Singleton.Debug($"准备发送数据，总大小: {bufferSize}字节");
                
                while (sentBytes < bufferSize)
                {
                    int bytesToSend = Math.Min(chunkSize, bufferSize - sentBytes);
                    int actualSent = SocketC.Send(buffer, sentBytes, bytesToSend, SocketFlags.None);
                    
                    if (actualSent == 0)
                    {
                        throw new SocketException((int)SocketError.ConnectionReset);
                    }
                    
                    sentBytes += actualSent;
                }
                
                Logger.Singleton.Debug($"数据发送成功，共发送: {sentBytes}字节");
                
                // 触发发送完成事件
                SocketSend?.Invoke(buffer, buffer.Length);
            }
            catch (SocketException ex)
            {
                Logger.Singleton.Error($"发送数据时发生Socket异常: {ex.SocketErrorCode} - {ex.Message}");
                
                // 根据不同的错误类型决定是否重连
                switch (ex.SocketErrorCode)
                {
                    case SocketError.ConnectionReset:
                    case SocketError.ConnectionAborted:
                    case SocketError.NotConnected:
                    case SocketError.TimedOut:
                    case SocketError.Shutdown:
                    case SocketError.NetworkUnreachable:
                    case SocketError.HostUnreachable:
                        // 这些错误表明连接已断开，需要重连
                        if (!ReConnnectFlag && !IsAutoStop)
                        {
                            Logger.Singleton.Info("检测到连接断开，触发重连机制");
                            // 使用延迟重连，避免立即重连可能导致的资源竞争
                            Task.Run(() =>
                            {
                                Thread.Sleep(1000); // 短暂延迟后重连
                                ReConnect(ex);
                            });
                        }
                        break;
                    case SocketError.WouldBlock:
                    case SocketError.NoBufferSpaceAvailable:
                        // 这些错误通常是临时性的，可以稍后重试
                        Logger.Singleton.Warn($"临时性发送错误，稍后可能需要重试: {ex.SocketErrorCode}");
                        break;
                    default:
                        Logger.Singleton.Error($"未预期的Socket错误: {ex.SocketErrorCode} - {ex.Message}");
                        break;
                }
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($"发送数据时发生未预期异常: {ex.Message}", ex);
            }

        }


        ///// <summary>
        ///// 接收数据
        ///// </summary>
        //public void receive()
        //{
        //    try
        //    {
        //        for (; ; )
        //        {
        //            //接收的字节数，当客户端下线时，receiveNumber=0
        //            int receiveNumber = SocketC.Receive(Buffer);

        //            //判断服务端是否下线，防止服务端下线时，客户端一直接收空消息
        //            if (receiveNumber == 0)
        //            {
        //                Logger.Singleton.Info("服务器掉线！尝试重连。。。。");
        //                // throw new SocketException();
        //            }

        //            //接收事件
        //            SocketReceive?.Invoke(Buffer, receiveNumber);
        //        }
        //    }
        //    catch (SocketException ex)
        //    {
        //        ReConnect(ex);
        //    }
        //    catch (ThreadInterruptedException)
        //    { }

        //}

        public void receive()
        {
            string threadId = Thread.CurrentThread.ManagedThreadId.ToString();
            Logger.Singleton.Info($"接收线程[{threadId}]已启动");
            
            // 避免在多屏环境下的空引用异常
            if (SocketC == null)
            {
                Logger.Singleton.Error("Socket为空，无法启动接收线程");
                return;
            }
            
            try
            {
                // 记录最后一次接收数据的时间，用于检测连接空闲
                DateTime lastReceiveTime = DateTime.Now;
                int idleCheckInterval = 30000; // 30秒空闲检查间隔
                
                while (!IsAutoStop) // 添加手动停止标志检查
                {
                    // 检查Socket状态，避免在多线程环境下访问已关闭的Socket
                    if (SocketC == null)
                    {
                        Logger.Singleton.Warn("Socket为空，退出接收循环");
                        break;
                    }
                    
                    // 使用更安全的方式检查Socket连接状态
                    bool isConnected = false;
                    try
                    {
                        isConnected = SocketC.Connected && !(SocketC.Poll(1, SelectMode.SelectRead) && SocketC.Available == 0);
                    }
                    catch (ObjectDisposedException)
                    {
                        Logger.Singleton.Info("Socket已被释放，退出接收循环");
                        break;
                    }
                    
                    if (!isConnected)
                    {
                        Logger.Singleton.Warn("检测到Socket连接已断开，退出接收循环");
                        break;
                    }
                    
                    // 检查连接空闲时间，在多屏环境下防止长时间无数据导致的连接断开
                    if ((DateTime.Now - lastReceiveTime).TotalMilliseconds > idleCheckInterval)
                    {
                        Logger.Singleton.Debug($"连接空闲超过{idleCheckInterval/1000}秒，发送心跳检测");
                        // 可以在这里添加心跳检测逻辑或其他保持连接的操作
                        lastReceiveTime = DateTime.Now;
                    }
                    
                    // 检查是否有数据可读，避免在没有数据时阻塞
                    if (!SocketC.Poll(1000000, SelectMode.SelectRead)) // 1秒超时，比之前的500ms更长，减少CPU使用率
                    {
                        continue; // 无数据可读，继续循环
                    }
                    
                    // 检查是否有可用数据，避免在连接断开时进入死循环
                    if (SocketC.Available == 0)
                    {
                        Logger.Singleton.Warn("Socket有可读事件但无可用数据，可能连接已断开");
                        break;
                    }
                    
                    int receiveNumber;
                    try
                    {
                        // 使用更安全的接收方法，限制最大接收字节数
                        receiveNumber = SocketC.Receive(Buffer, 0, Math.Min(Buffer.Length, SocketC.Available), SocketFlags.None);
                        lastReceiveTime = DateTime.Now; // 更新最后接收时间
                    }
                    catch (SocketException ex)
                    {
                        // 区分不同类型的Socket错误
                        Logger.Singleton.Error($"接收数据时发生Socket异常: {ex.SocketErrorCode} - {ex.Message}");
                        
                        if (ex.SocketErrorCode == SocketError.ConnectionReset ||
                            ex.SocketErrorCode == SocketError.ConnectionAborted ||
                            ex.SocketErrorCode == SocketError.TimedOut ||
                            ex.SocketErrorCode == SocketError.Shutdown ||
                            ex.SocketErrorCode == SocketError.NetworkDown ||
                            ex.SocketErrorCode == SocketError.NetworkReset)
                        {
                            Logger.Singleton.Info($"连接断开: {ex.SocketErrorCode}，准备重连");
                            break;
                        }
                        else if (ex.SocketErrorCode == SocketError.WouldBlock ||
                                 ex.SocketErrorCode == SocketError.IOPending)
                        {
                            // 这些错误通常是临时性的，可以继续循环
                            Logger.Singleton.Debug($"临时性Socket错误: {ex.SocketErrorCode}，继续监听");
                            Thread.Sleep(10); // 短暂睡眠避免CPU占用过高
                            continue;
                        }
                        throw; // 重新抛出其他Socket异常
                    }

                    if (receiveNumber == 0)
                    {
                        Logger.Singleton.Info("检测到服务端关闭连接(接收字节数为0)，准备重连...");
                        break; // 正常退出循环，不抛异常
                    }

                    try
                    {
                        Logger.Singleton.Debug($"接收到数据，大小: {receiveNumber}字节");
                        
                        // 创建接收数据的副本，避免多屏环境下的数据竞争
                        byte[] receiveBuffer = new byte[receiveNumber];
                        Array.Copy(Buffer, receiveBuffer, receiveNumber);
                        
                        // 在单独的任务中处理数据，避免阻塞接收线程
                        Task.Run(() =>
                        {
                            try
                            {
                                SocketReceive?.Invoke(receiveBuffer, receiveNumber);
                            }
                            catch (Exception processEx)
                            {
                                Logger.Singleton.Error($"处理接收到的数据时出错: {processEx.Message}", processEx);
                            }
                        });
                    }
                    catch (Exception bufferEx)
                    {
                        Logger.Singleton.Error($"复制接收数据缓冲区时出错: {bufferEx.Message}", bufferEx);
                    }
                    
                    // 短暂睡眠，避免CPU占用过高
                    Thread.Sleep(5);
                }
            }
            catch (SocketException ex)
            {
                Logger.Singleton.Error($"接收线程[{threadId}]发生网络异常: {ex.SocketErrorCode} - {ex.Message}", ex);
            }
            catch (ObjectDisposedException)
            {
                // Socket 已被外部关闭（如用户主动断开），无需重连
                Logger.Singleton.Info($"接收线程[{threadId}]: Socket已被释放，退出接收线程");
                return;
            }
            catch (ThreadInterruptedException)
            {
                // 线程被中断，正常退出
                Logger.Singleton.Info($"接收线程[{threadId}]被中断，正常退出");
                return;
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($"接收线程[{threadId}]发生未预期异常: {ex.Message}", ex);
            }
            finally
            {
                // 注意：这里不要直接 Close(SocketC)
                // 而是让 ReConnect 或连接管理器决定是否关闭并重建
                if (!IsAutoStop) // 仅在非手动停止情况下才尝试重连
                {
                    Logger.Singleton.Info($"接收线程[{threadId}]退出，触发重连机制");
                    // 使用延迟重连，避免在多屏环境下的资源竞争
                    Task.Run(() =>
                    {
                        Thread.Sleep(500); // 短暂延迟后重连
                        ReConnect(null); // 由 ReConnect 内部处理旧连接的关闭
                    });
                }
                Logger.Singleton.Info($"接收线程[{threadId}]已完全退出");
            }
        }

        //private void ReConnect()
        //{
        //    // 先安全关闭旧连接（如果还存在）
        //    try
        //    {
        //        SocketC?.Close(); // 或 Shutdown + Close
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.Singleton.Warn("关闭旧连接时出错", ex);
        //    }
        //    finally
        //    {
        //        SocketC = null;
        //    }

        //    // 然后尝试新建连接
        //    // ConnectToServer(); // 你的连接逻辑

        //    ReConnect(null);
        //}



        /// <summary>
        /// 释放所有套间字
        /// </summary>
        public void Close()
        {
            // 不再设置ReConnnectFlag = true，允许重连
            ConnectFlag = false;
            //中断线程
            if (ListenMsgTh != null && ListenMsgTh.IsAlive)
            {
                try
                {
                    ListenMsgTh.Interrupt();
                }
                catch (Exception ex)
                {
                    Logger.Singleton.Error("中断监听线程出错：" + ex.Message);
                }
            }
            if (ReConnectTh != null && ReConnectTh.IsAlive)
            {
                try
                {
                    ReConnectTh.Interrupt();
                }
                catch (Exception ex)
                {
                    Logger.Singleton.Error("中断重连线程出错：" + ex.Message);
                }
            }
            //关闭连接
            if (SocketC != null && SocketC.Connected)
            {
                try
                {
                    SocketC.Shutdown(SocketShutdown.Both);
                }
                catch (SocketException ex)
                {
                    Logger.Singleton.Error("关闭连接时出错：" + ex.Message);
                }
                finally
                {
                    SocketC.Close();
                    SocketC = null; // 确保Socket被重置
                }
            }
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~TcpClientHelper()
        {
            Close();
        }
    }

}
